import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { DepartmentEntity } from './department.entity';
import { Between, Not, TreeRepository, getManager, Brackets } from 'typeorm';
import * as dayjs from 'dayjs';
// import { skip } from 'rxjs/operators';
type captcha = {
  key: string;
  captcha: string;
  validTime?: string;
};

@Injectable()
export class DepartmentService {
  constructor(
    @InjectRepository(DepartmentEntity)
    private readonly departmentRepository: Repository<DepartmentEntity>,
  ) {}

  async getDepartmentList(param) {
    return await this.departmentRepository.find({ where: param });
  }
  async getDepartmentTreeList(param) {
    const {
      current,
      pageSize,
      noPagination,
      orderParam,
      createDateRange,
      usersIds,
      ...restParam
    } = param;

    let where = {
      ...restParam,
      createDate: Between(createDateRange?.[0], createDateRange?.[1]),
    };
    if (!createDateRange) {
      delete where.createDate;
    }

    //排序逻辑
    const order = {};
    Object.keys(orderParam || {}).map(item => {
      order[`department.${item}`] = orderParam[item];
    });
    const manager = getManager();
    return await manager
      .getTreeRepository(DepartmentEntity)
      .findTrees({ relations: ['users','leaders'] });
  }

  async getDepartmentTree(param) {
    const manager = getManager();

    return await manager
      .getTreeRepository(DepartmentEntity)
      .createDescendantsQueryBuilder(
        'department',
        'departmentClosure',
        new DepartmentEntity(),
      )
      .leftJoinAndSelect('department.users', 'users')
      .leftJoinAndSelect('department.children', 'children')
      .leftJoinAndSelect('children.users', 'children.users')
      .leftJoinAndSelect('children.children', 'children.children')
      .where({})
      .getMany();
  }
  async getDepartment(param) {
    return await this.departmentRepository
      .createQueryBuilder('department')
      .leftJoinAndSelect('department.users', 'users')
      .leftJoinAndSelect('department.leaders', 'leaders')
      .where(param)
      .getOne();
  }
  async saveDepartment(param) {
    const { pid, users = [], leaders = [], ...restParam } = param;
    const manager = getManager();
    let department = new DepartmentEntity();
    Object.assign(department, restParam);
    // department.users = users.map(id => {
    //   return { id };
    // });
    department.leaders = leaders.map(id => {
      return { id };
    });
    !department.id &&
      (department.createDate = dayjs().format('YYYY-MM-DD HH:mm:ss'));
    if (pid) {
      const root = new DepartmentEntity();
      root.id = pid;
      department.parent = root;
      return await manager.save(department);
    } else {
      return await manager.save(department);
    }
  }
  async delDepartmentList(param) {
    const { idList } = param;
    let data = await this.departmentRepository.findByIds(idList);
    return await this.departmentRepository.remove(data);
  }
}
